<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\SeckillModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use function GuzzleHttp\json_encode;

class SeckillController extends Controller
{

    // 秒杀开始前
    public function before(Request $request,SeckillModel $seckillModel){
        //数据库操作
        $sqlQuery = "select id,lw_stock from lw_seckill";
        $result = \DB::select(\DB::raw($sqlQuery));
        $data = json_decode(json_encode($result),true);
        //redis连接
        Redis::select(3);      //指定redis库
        foreach ($data as $k => $v){
            for ($i=1;$i<$v['lw_stock'];$i++){
                Redis::lpush('lw_seckill'.$v['id'],$i);
            }
        }
        dump($data);
    }

    // 秒杀中
    public function index(Request $request)
    {
        $data = SeckillModel::all();
        return view('admin.seckill.index',compact('data'));
    }

    //秒杀倒计时
    public function countdown(){
        $sqlQuery = "select * from lw_seckill";
        $result = \DB::select(\DB::raw($sqlQuery));
        $data = json_decode(json_encode($result),true);
        foreach ($data as $k => $v){
            $startTime = time();
            $endTime = $v['lw_time_over'];
            $remainTime = $endTime-$startTime;
            //开始时间和结束时间之间的相差的描述
            $hour = floor($remainTime/3600);
            //1小时是3600秒，所有的秒数除以3600秒，是不就转换成小时了
            $minute = floor(($remainTime-$hour*3600)/60);
            $second = $remainTime-$hour*3600-$minute*60;
            $data[$k]['hour'] = $hour;
            $data[$k]['minute'] = $minute;
            $data[$k]['second'] = $second;
        }
        return $data;
    }

    // 秒杀后
    public function behind(Request $request){
        $id = $request->get("id");
        Redis::select(3);
        $key = 'lw_seckill'.$id;
        if (Redis::llen($key)>0){
            Redis::lpop($key);
            $sql = \DB::update("update lw_seckill set lw_stock=lw_stock-1 where id=$id");
            $order_id = date("Ymd",time()).md5(rand(100,999));
            $addtime = time();
            return ['code'=>1,'msg'=>'秒杀成功'];
        }else{
            return ['code'=>0,'id'=>$id,'msg'=>'此商品已秒杀结束'];
        }
    }

}
